package com.romotc.qqrobot.bean;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.json.JSONObject;

import com.romotc.oschina.bean.POJO;
import com.romotc.qqrobot.config.QQUrlWatcherConfigService;
import com.romotc.qqrobot.config.bean.QQUrlWatcherConfig;
import com.romotc.qqrobot.webqq.WebQQConstant;
import com.romotc.qqrobot.webqq.qqInterfaceLog.QQInterfaceLog;
import com.romotc.scache.RequestSpy;

public class QQData extends POJO {

	/////////类数据//////////////
	private long urlId;

	private java.sql.Timestamp startTime;

	private java.sql.Timestamp endTime;
	
	private long reqId;
	
	/**
	 * 发送给服务器的请求信息 包含request.params && Post的数据
	 */
	private String reqInfo;
	
	/**
	 * 服务器的响应体
	 */
	private String result;
	
	/**
	 * 请求头
	 */
	private ArrayList<String> reqHeaders;
	
	/**
	 * 请求模板号 默认为0：非模板；如果是模板则该版本号最大的为最新模板
	 * RomUnDo 以后将请求模板表独立出来
	 */
	private int templetVersion = 0;
	
	/**
	 * 该数据的来源QQ
	 */
	private String fromQq;
	
	////////////以下信息是RequestSpy中有的未记录到数据库中的////////////
	
	/**
	 * 数据缓存:请求cookie信息 
	 * 作为数据缓存使用，第一次通过解析reqHeaders获取 以后就直接返回解析好的对象
	 */
	private JSONObject reqCookies;
	
	/**
	 * 服务器的响应头
	 */
	private ArrayList<String> resHeaders;
	
	/**
	 * 服务器的响应 编码
	 */
	private String resCharSet;
	
	
	
	/////////////////构造方法/////////////////
	public QQData()
	{
		super();
	}
	
	public QQData(long endTime, long reqStartTime, 
			long reqId, String reqInfo, String result)
	{
		if(endTime != 0) {
			this.endTime = new java.sql.Timestamp(endTime);
		}
		
		if(reqStartTime != 0) {
			this.startTime = new java.sql.Timestamp(reqStartTime);
		}
		
		this.reqId = reqId;

		this.reqInfo = reqInfo;//java.net.URLEncoder.encode(reqInfo, "utf-8");
		this.result = result;//java.net.URLEncoder.encode(result, "utf-8");
	
//		try {
//			this.reqInfo = reqInfo;//java.net.URLEncoder.encode(reqInfo, "utf-8");
//			this.result = result;//java.net.URLEncoder.encode(result, "utf-8");
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
		
	}
	
	public QQData(RequestSpy rqSpy) {

		this(rqSpy.getReqEndTime(), rqSpy.getReqStartTime(),
				rqSpy.getReqSN(), rqSpy.getReqInfos(), rqSpy.getResBody());
		
		QQUrlWatcherConfig config = QQUrlWatcherConfigService.getConfigByUrl(rqSpy.getURL(), null);
		
		String ptui_loginuin = rqSpy.getReqCookiesJson().optString(WebQQConstant.Cookie_ptui_loginuin);
		//发现未配置的url自动添加
		if(StringUtils.isNotBlank(ptui_loginuin))
		if((config == null || "*".equals(config.getUrl())) && !WebQQConstant.isUi(rqSpy.getURL())) {
			config = new QQUrlWatcherConfig();
			String url = rqSpy.getURL();
			int idx = url.indexOf("?");
			if(idx != -1) 
				url = url.substring(0, idx);
			
			if(!url.endsWith(".com/") && !url.endsWith(".com")) {
				config.setUrl(url + "*");
				config.setProcessOrder(-9);
				config.setCatchingClass("com.romotc.qqrobot.webqq.qqInterfaceCatching.DefaultUrl_Catching");
				config.setLogLevel(1001);
				config.setLogFileName("access.log");
				config.setNote("Default自动添加 for " + rqSpy.getURL());
				System.err.println("create url config for :" + url);
				config.Save();
				//刷新缓存
				QQInterfaceLog.getAllUrlConfig();
			}
		}
		
		this.urlId = config == null ? getUrlIdFromURL(rqSpy.getURL()) : config.getId();
		
		
		if(rqSpy.getReqHeaders() != null && !rqSpy.getReqHeaders().isEmpty()){
			
			String headers = StringUtils.join(rqSpy.getReqHeaders(), ", ");
			this.setReqHeadersStr(headers);
		}
		
		QQLogedin curQq = QQLogedin.getCurQqLogedIn(rqSpy);
		if(curQq != null) {
			this.setFromQq(curQq.getUin());
		}
		
	}
	
	/**
	 * build QQData from RequestSpy
	 * @param rqSpy
	 * @return
	 */
	public static QQData buildQQTransData(RequestSpy rqSpy) {
		if(rqSpy.getURL().indexOf(URL_POLL2) != -1 
				&& "{\"retcode\":102,\"errmsg\":\"\"}".equals(rqSpy.getResBody())) {
			return null;
		}
		return new QQData(rqSpy);
	}
	
	
	
	
	public static String URL_SEND_BUDDY_MSG2 = "http://d.web2.qq.com/channel/send_buddy_msg2";
	
	/**
	 * 获取好友信息（获取自己信息也通过该接口）
	 */
	public static String URL_GET_FRIEND_INFO2 = "http://s.web2.qq.com/api/get_friend_info2";
	public static String URL_GET_USER_FRIENDS = "http://s.web2.qq.com/api/get_user_friends2";
	public static String URL_POLL2 = "http://d.web2.qq.com/channel/poll2";
	public static String URL_GET_GROUP_NAME_LIST_MASK2 = "http://s.web2.qq.com/api/get_group_name_list_mask2";
	public static String URL_GET_ONLINE_BUDDIES2 = "http://d.web2.qq.com/channel/get_online_buddies2";
	public static String URL_GET_DISCU_LIST_NEW2 = "http://d.web2.qq.com/channel/get_discu_list_new2";
	public static String URL_GET_SINGLE_LONG_NICK2 = "http://s.web2.qq.com/api/get_single_long_nick2";
	public static String URL_GET_RECENT_LIST2 = "http://d.web2.qq.com/channel/get_recent_list2";
	public static String URL_GET_QQ_LEVEL2 = "http://s.web2.qq.com/api/get_qq_level2";
	public static final String URL_GET_FRIEND_UIN2 = "http://s.web2.qq.com/api/get_friend_uin2";
	public static final String URL_LOGIN2 = "http://d.web2.qq.com/channel/login2";
	
	private int getUrlIdFromURL(String url) {
		if(url.indexOf(URL_SEND_BUDDY_MSG2) != -1) {
			return 1;
		}else if(url.indexOf(URL_GET_FRIEND_INFO2) != -1) {
			return 2;
		}else if(url.indexOf(URL_GET_USER_FRIENDS) != -1) {
			return 3;
		}else if(url.indexOf(URL_POLL2) != -1) {
			return 4;
		}else if(url.indexOf(URL_GET_GROUP_NAME_LIST_MASK2) != -1) {
			return 5;
		}else if(url.indexOf(URL_GET_ONLINE_BUDDIES2) != -1) {
			return 6;
		}else if(url.indexOf(URL_GET_DISCU_LIST_NEW2) != -1) {
			return 7;
		}else if(url.indexOf(URL_GET_SINGLE_LONG_NICK2) != -1) {
			return 8;
		}else if(url.indexOf(URL_GET_RECENT_LIST2) != -1) {
			return 9;
		}else if(url.indexOf(URL_GET_QQ_LEVEL2) != -1) {
			return 10;
		}else if(url.indexOf(URL_GET_FRIEND_UIN2) != -1) {
			return 11;
		}else if(url.indexOf(URL_LOGIN2) != -1) {
			return 12;
		}
		
		return 0;
	}

	
	/////////////getter && setter/////////
	public long getUrlId() {
		return urlId;
	}
	public void setUrlId(long urlId) {
		this.urlId = urlId;
	}

	public java.sql.Timestamp getStartTime() {
		return startTime;
	}

	public void setStartTime(java.sql.Timestamp startTime) {
		this.startTime = startTime;
	}

	public Date getEndTime() {
		return endTime;
	}

	public void setEndTime(java.sql.Timestamp endTime) {
		this.endTime = endTime;
	}

	public long getReqId() {
		return reqId;
	}

	public void setReqId(long reqId) {
		this.reqId = reqId;
	}

	public String getReqInfo() {
		return reqInfo;
	}
	public void setReqInfo(String reqInfo) {
//		try {
//			this.reqInfo = java.net.URLDecoder.decode(reqInfo, "utf-8");
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		this.reqInfo = reqInfo;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
//		try {
//			this.result = java.net.URLDecoder.decode(result, "utf-8");
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		this.result = result;
	}
	
	
	
	///////////main///////////
	public static void main(String args[]){
		QQData qData = new QQData();
//		
//		qData = qData.Get(12);
//		System.out.println(qData.getId());
//		System.out.println(qData.getReqInfo());
//		System.out.println(qData.getResult());
		
		int tablesize = qData.TotalCount();
		int curIdx = 0;
		int page = 1;
		List<QQData> qdList;
		while(curIdx < tablesize) {
			qdList = (List<QQData>)qData.List(page++, 5);
			curIdx += 5;
			int j = 0;
			while(j < qdList.size()) {
				QQData qData2 = qdList.get(j++);
				System.out.print(qData2.getUrlId());
				System.out.print(" reqInfo:");
				System.out.print(qData2.getReqInfo());
				System.out.print(" resInfo:");
				System.out.print(qData2.getResult());
			}
		}

		
	}

	private String reqHeadersStr;
	public String getReqHeadersStr() {
		if(StringUtils.isNotBlank(reqHeadersStr))
			return reqHeadersStr;
		
		if(reqHeaders != null && !reqHeaders.isEmpty())
		{
			this.reqHeadersStr = StringUtils.join(reqHeaders, ", ");
		}
		return reqHeadersStr;
	}

	@JsonIgnore
	public ArrayList<String> reqHeaderList() {
		return this.reqHeaders;
	}
	
	/**
	 * 
	 * @param reqHeaders header1: value, header2: value
	 */
	public void setReqHeadersStr(String reqHeaders) {
		this.reqHeadersStr = reqHeaders;
		
		//通过string解析为list
		if(StringUtils.isNotBlank(reqHeadersStr)) {
			this.reqHeaders = new ArrayList<String>();
			String[] headers = reqHeaders.split(", ");
			if(headers != null && headers.length > 0) {
				int i = 0;
				for(String header : headers) {
					this.reqHeaders.add(headers[i++]);
				}
			}
		}
	}

	public int getTempletVersion() {
		return templetVersion;
	}

	public void setTempletVersion(int templetVersion) {
		this.templetVersion = templetVersion;
	}

	public String getFromQq() {
		return fromQq;
	}

	public void setFromQq(String fromQq) {
		this.fromQq = fromQq;
	}
}
